﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Atom.NetFrame
{

    public class SocketModel
    {
        /// <summary>
        /// 一级协议，用于确认所属模块
        /// </summary>
        public byte Type { get; set; }
        /// <summary>
        /// 二级协议，用于确认模块下的子模块
        /// </summary>
        public int Area { get; set; }
        /// <summary>
        /// 三级协议，用于消息逻辑的请求
        /// </summary>
        public int Command { get; set; }
        /// <summary>
        /// 消息内容
        /// </summary>
        public byte[] Message { get; set; }

        public SocketModel()
        {

        }

        public SocketModel(byte t, int a, int c, byte[] m)
        {
            this.Type = t;
            this.Area = a;
            this.Command = c;
            this.Message = m;
        }



        /// <summary>
        /// 序列化
        /// </summary>
        /// <returns></returns>
        public byte[] Encode()
        {
            byte[] buffer = null;
            using (MemoryStreamExt msTemp = new MemoryStreamExt())
            {
                msTemp.WriteByte(Type);
                //msTemp.WriteInt(Area); 服务器发个客户端不需要这个区域
                msTemp.WriteInt(Command);
                if (Message != null)
                {
                    msTemp.Write(Message, 0, Message.Length);
                }
                buffer = new byte[msTemp.Length];
                buffer = msTemp.ToArray();
            }

            return buffer;
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <returns></returns>
        public static SocketModel Decode(byte[] buffer)
        {
            int len = buffer.Length;
            byte type;
            int area;
            int command;
            byte[] newBuffer = null;
            using (MemoryStreamExt msTemp = new MemoryStreamExt(buffer))
            {
                type = (byte)(msTemp.ReadByte());
                area = msTemp.ReadInt();
                command = msTemp.ReadInt();

                if (len > 9)
                {
                    newBuffer = new byte[len - 9];
                    msTemp.Read(newBuffer, 0, len - 9);
                }
            }

            SocketModel model = new SocketModel(type, area, command, newBuffer);
            return model;
        }
    }
}
